package com.uzai.console.web.alipaymch;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenInviteOrderCreateRequest;
import com.alipay.api.response.AlipayOpenInviteOrderCreateResponse;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.common.exception.BusinessException;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.AliPayConfig;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.alipaymch.AlipayMchAppAuthSignUrlDao;
import com.uzai.console.dto.alipaymch.AlipayMchAuthDto;
import com.uzai.console.dto.alipaymch.AlipayMchAuthIdDto;
import com.uzai.console.dto.alipaymch.AlipayMchAuthQuery;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.SysConfigMapper;
import com.uzai.console.service.alipaymch.AlipayMchAppAuthService;
import com.uzai.console.vo.alipaymch.AlipayMchAppAuthSignUrlVo;
import com.uzai.console.vo.alipaymch.AlipayMchAuthVo;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

/**
 * 支付宝第三方应用商户授权
 * @Auther: jianghan
 * @Date: 2021/12/14 14:04
 * @Description:
 */
@RestController
@Api(value = "支付宝授权",tags = "第三方支付宝|支付宝授权")
@ApiSort(101)
public class AlipayMchAppAuthController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AlipayMchAppAuthController.class);

    @Autowired
    private AlipayMchAppAuthService alipayMchAppAuthService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 获取授权地址
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取授权地址", notes = "获取授权地址", response = AlipayMchAppAuthSignUrlVo.class)
    @ApiOperationSupport(order = 1)
    @GetMapping("/alipay/mchappauth/url")
    public Object mchAppAuthUrl(){
        Long merId = getLoginInfo().getMerId();
        AlipayMchAppAuthSignUrlVo alipayMchAppAuthUrlVo = new AlipayMchAppAuthSignUrlVo();
        String url = StringUtils.join(uzaiConsoleSysConfig.getAlipayMchauthUrl(),"&state=",merId);
        logger.info("mch app auth url :{}",url);
        alipayMchAppAuthUrlVo.setUrl(url);
        return alipayMchAppAuthUrlVo;
    }

    /**
     * 获取商户签约地址
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取商户签约地址", notes = "获取商户签约地址", response = AlipayMchAppAuthSignUrlVo.class)
    @ApiOperationSupport(order = 2)
    @GetMapping("/alipay/mchinvitesign/url")
    public Object mchInviteSignUrl(){
        return alipayMchAppAuthService.mchInviteSignUrl();
    }

    @ApiOperation(value = "获取商户签约页面跳转表单数据", notes = "获取商户签约页面跳转表单数据", response = AlipayMchAppAuthSignUrlVo.class)
    @ApiOperationSupport(order = 3)
    @PostMapping("/alipay/mchinvitesign/url/findById")
    public Object findAlipayMchAppAuthSignUrl(@RequestBody AlipayMchAppAuthSignUrlDao alipayMchAppAuthSignUrlDao) {
        return alipayMchAppAuthService.findAlipayMchAppAuthSignUrl(alipayMchAppAuthSignUrlDao);
    }

    /**
     * 授权结果（支付宝回调函数）
     * @return
     */
    @ApiOperation(value = "授权结果（支付宝回调函数）", notes = "授权结果（支付宝回调函数）", hidden = true)
    @ApiOperationSupport(order = 3)
    @GetMapping("/alipay/mchappauth/result")
    public void mchAppAuthResult(String app_id,String app_auth_code, String state) throws Exception{
        logger.info("app_id:{},app_auth_code:{},state:{}",new Object[]{app_id,app_auth_code,state});
        String resultUrl = uzaiConsoleSysConfig.getAlipayMchauthReturnurl();
        try {
            alipayMchAppAuthService.mchAppAuthToken(app_id, app_auth_code, state);
            // 成功
            resultUrl = resultUrl+"?state=1";
        } catch (Exception e) {
            logger.error("err:",e);
            String msg = "授权失败";
            if (e instanceof BusinessException){
                BusinessException be = (BusinessException) e;
                msg = be.getMessage();
            }

            // 失败
            try {
                resultUrl = resultUrl+"?state=0&msg="+ URLEncoder.encode(msg,"UTF-8");
            } catch (Exception e1) {
                logger.error("err:",e1);
            }
        }
        getResponse().sendRedirect(resultUrl);
    }

    @ApiOperation(value = "分页查询支付宝授权列表", notes = "分页查询支付宝授权列表", response = AlipayMchAuthVo.class)
    @ApiOperationSupport(order = 4)
    @PostMapping("/alipay/mchappauth/findAlipayMchAuthList")
    public Object findAlipayMchAuthList(@RequestBody AlipayMchAuthQuery alipayMchAuthQuery){
        return alipayMchAppAuthService.findAlipayMchAuthList(alipayMchAuthQuery);
    }

    @SystemLogType(model = SystemModelEnum.AlipayMchAuth, type = OperationTypeEnum.DELETE)
    @ApiOperation(value = "删除支付宝授权", notes = "删除支付宝授权")
    @ApiOperationSupport(order = 5)
    @PostMapping("/alipay/mchappauth/deleteAlipayMchAuth")
    public Object deleteAlipayMchAuth(@RequestBody AlipayMchAuthIdDto alipayMchAuthIdDto){
        alipayMchAppAuthService.deleteAlipayMchAuth(alipayMchAuthIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AlipayMchAuth, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "编辑支付宝授权备注", notes = "编辑支付宝授权备注" )
    @ApiOperationSupport(order = 6)
    @PostMapping("/alipay/mchappauth/updateRemark")
    public Object updateRemark(@RequestBody AlipayMchAuthDto alipayMchAuthDto){
        alipayMchAppAuthService.updateRemark(alipayMchAuthDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.AlipayMchAuth, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "编辑支付宝授权转账信息", notes = "编辑支付宝授权转账信息" )
    @ApiOperationSupport(order = 6)
    @PostMapping("/alipay/mchappauth/updateTransInfo")
    public Object updateTransInfo(@RequestBody AlipayMchAuthDto alipayMchAuthDto){
        alipayMchAppAuthService.updateTransferinfo(alipayMchAuthDto);
        return true;
    }

    @ApiOperation(value = "查询支付宝授权下拉列表框", notes = "查询支付宝授权下拉列表框", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 7)
    @PostMapping("/alipay/mchappauth/findAlipayMchAuthListSelect")
    public Object findAlipayMchAuthListSelect(){
        AlipayMchAuthQuery alipayMchAuthQuery = new AlipayMchAuthQuery();
        alipayMchAuthQuery.setMerId(getLoginInfo().getMerId());
        return alipayMchAppAuthService.findAlipayMchAuthListSelect(alipayMchAuthQuery);
    }

}
